package exercise;

import JZOffer.ListNode;
import JZOffer.MySingleList;

public class LCode24 {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode ans = head.next;
        swap(null, head, head.next);
        ListNode p = head;
        while (p != null && p.next != null && p.next.next != null) {
            swap(p, p.next, p.next.next);
            p = p.next.next;
        }
        return ans;
    }

    private void swap(ListNode p, ListNode node1, ListNode node2) {
        if (p != null) {
            p.next = node2;
        }
        node1.next = node2.next;
        node2.next = node1;
    }

    public static void main(String[] args) {
        LCode24 lCode24 = new LCode24();
        MySingleList list = new MySingleList();
        list.addLast(1);
//        list.addLast(2);
//        list.addLast(3);
//        list.addLast(4);
        list.head = lCode24.swapPairs(list.head);
        list.display();
    }
}
